import {
	userListApi,
} from '@utils/apis'
import {
	userAdd,
	userEdit,
	userDel,
	submit,
	cancel,
} from "./user-methods";

module.exports = function initUserPage(user) {
	let comps = {
		formDialog: $("#user-form-dialog"),
		dataGrid: $("#main-tabs-user"),
		userForm: $("#user-form"),
		userName: $("#user-form-username"),
		userEmail: $("#user-form-email"),
		userPassword: $("#user-form-pwd"),
		userNickName: $("#user-form-nickname"),
		userRealName: $("#user-form-mobile"),
		formBtnSave: $("#user-form-btn-save"),
		formBtnCancel: $("#user-form-btn-cancel"),
	}
	// let funcs = user.funcMap['user_management']
	initDataGrid(comps, user)
	initEditDailog(comps, user)
}

function initDataGrid(comps, user) {
	let {
		dataGrid,
		formDialog,
	} = comps
	let options = {
		fit: true,
		fitColumns: true,
		rownumbers: true,
		singleSelect: true,
		toolbar: [],
		columns: [
			[{
				field: 'user_id',
				title: 'ID',
				width: 80
			}, {
				field: 'username',
				title: '用户名',
				width: 80
			}, {
				field: 'nickname',
				title: '昵称',
				width: 80,
			}, {
				field: 'mail',
				title: '邮箱',
				width: 80,
			}, {
				field: 'create_time',
				title: '创建时间',
				width: 80,
			}, {
				field: 'orgpassword',
				title: '初始密码',
				width: 80,
			}, {
				field: 'last_login_date',
				title: '最近登录时间',
				width: 80,
			}]
		],
	}
	// 添加用户
	if (user.func_ids.indexOf('user_add') > -1) {
		options.toolbar.push({
			iconCls: 'icon-add',
			text: '新建',
			handler() {
				userAdd(comps, user, 'user_add')
			}
		}, '-')
	}
	// 修改用户信息
	if (user.func_ids.indexOf('user_modify') > -1) {
		options.toolbar.push({
			iconCls: 'icon-edit',
			text: '修改',
			handler() {
				userEdit(comps, user, 'user_modify')
			}
		}, '-')
	}
	// 删除用户
	if (user.func_ids.indexOf('user_del') > -1) {
		options.toolbar.push({
			iconCls: 'icon-remove',
			text: '删除',
			handler() {
				userDel(comps, user, 'user_del')
			}
		})
	}
	if (user.func_ids.indexOf('user_list') > -1) {
		options.url = user.funcMap['user_list'].func_url
	}
	dataGrid.datagrid(options)
}

function initEditDailog(comps, user) {
	let {
		formBtnSave,
		formBtnCancel,
	} = comps
	formBtnSave.linkbutton({
		text: '保存',
		iconCls: 'icon-save',
		onClick() {
			submit(comps, user)
		},
	})
	formBtnCancel.linkbutton({
		text: '取消',
		iconCls: 'icon-cancel',
		onClick() {
			cancel(comps)
		},
	})
}